package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.domain.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("file")
public class FileController {

    //文件上传
    @RequestMapping("upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("image")MultipartFile image){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tGey8tVvqfYWGdmNnDX";
        String accessKeySecret = "gAWjuFfNPJEYA7GBY5VXpF1G2MaFzl";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ccc828";

        //图片上传问价加
        String imageDir = "group1/M00/00/00/";
        String filename = image.getOriginalFilename();

        String objectName = imageDir+filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName,image.getInputStream());
        } catch (Exception ce) {
            System.out.println(ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        StringBuilder sb = new StringBuilder();
        String s = sb.append(http).append(bucketName).append(".").append(endpoint).append("/").append(objectName).toString();
        System.out.println(s);
        return  AjaxResult.OK().setData(s);
    }
}
